package com.ld.shieldsb.common.core.util.solr;

import org.apache.http.client.HttpClient;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpClientUtil;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.params.ModifiableSolrParams;

import com.ld.shieldsb.common.core.util.StringUtils;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
public class SolrAuthClient extends HttpSolrClient {
    /**
     * @Fields serialVersionUID
     */
    private static final long serialVersionUID = -6082166921604890916L;
    private String userName;
    private String password;
    private SolrClient solrClient;

    protected SolrAuthClient(Builder builder) {
        super(builder);
    }

    public static SolrAuthClient build(String baseUrl, String userName, String password) {
        Builder builder = new HttpSolrClient.Builder(baseUrl).withConnectionTimeout(10000).withSocketTimeout(60000);
        if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)) {
            ModifiableSolrParams params = new ModifiableSolrParams();
            params.set(HttpClientUtil.PROP_BASIC_AUTH_USER, userName); // 从配置文件中获取SOLR用户名
            params.set(HttpClientUtil.PROP_BASIC_AUTH_PASS, password); // 从配置文件中获取SOLR密码
            HttpClient client = HttpClientUtil.createClient(params);
            builder.withHttpClient(client);
        }
        HttpSolrClient client = builder.build();
        SolrAuthClient saClient = new SolrAuthClient(builder);
        saClient.setSolrClient(client);
        saClient.setUserName(userName);
        saClient.setPassword(password);
        return saClient;
    }

}
